package com.hc.conferencecheck.interceptors;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hc.conferencecheck.entity.ResultMsg;
import com.hc.conferencecheck.entity.ResultStatusCode;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义拦截器，用于登录验证
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println(">>>MyInterceptor2>>>>>>>在请求处理之前进行调用（Controller方法调用之前）");
        //获取请求路径
        String requestURL = request.getRequestURL().toString();
        //用户申请会议、签到、我的会议时必须先登录
        if (requestURL.contains("/applyConference") || requestURL.contains("/editSignCode") || requestURL.contains("/selectConferenceApplied")) {
            //如果包含指定请求路径，进行登录验证，如果验证通过就放行，否则return false;
            System.out.println("对于指定路径进行登录验证");

            HttpSession session = request.getSession();
            Object user = session.getAttribute("user");

            if (user == null) {
                //session,说明用户还没登录
                return false;
            } else {
                return true;
            }
        }
        //对于非指定路径，直接放行；
        return true;// 只有返回true才会继续向下执行，返回false取消当前请求
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        System.out.println(">>>MyInterceptor2>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println(">>>MyInterceptor2>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
    }

    private void returnErrorMessage(HttpServletResponse response, String errorMessage) throws IOException {
        //设置返回数据类型
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        //将返回结果转换为json，使用流对象输出
        ResultMsg resultMsg = new ResultMsg(ResultStatusCode.EORROR.getCode(), ResultStatusCode.EORROR.getMsg(), "当前用户尚未登录，请先登录");
        String jsonString = JSON.toJSONString(resultMsg);
        out.print(jsonString);
        out.flush();
    }
}
